package com.lsf.dunlian.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Contacts;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.lsf.dunlian.Myappliction;
import com.lsf.dunlian.R;
import com.lsf.dunlian.adapter.FileRecyclerViewAdapter;
import com.lsf.dunlian.config.PreferenceUtil;
import com.lsf.dunlian.config.Urls;
import com.lsf.dunlian.constant.Constant;
import com.lsf.dunlian.databinding.ActivityMemberBinding;
import com.lsf.dunlian.entity.BaseEntity;
import com.lsf.dunlian.entity.BasicHouse;
import com.lsf.dunlian.entity.BasicMember;
import com.lsf.dunlian.entity.FileEntity;
import com.lsf.dunlian.entity.HouseModel;
import com.lsf.dunlian.entity.UserInfoVo;
import com.lsf.dunlian.utils.audio.ContentUriUtil;
import com.lsf.dunlian.utils.audio.UploadImage;
import com.mylhyl.superdialog.SuperDialog;
import com.mylhyl.superdialog.res.values.ColorRes;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MemberActivity extends FragmentActivity {
    private LayoutInflater inflater;
    private ActivityMemberBinding binding;
    private List<String> basicHouseList = new ArrayList<>();
    private List<String> basicDemandList = new ArrayList<>();
    private List<String> a= Arrays.asList("金融","电信","教育","高科技","政府","制造业","服务业","零售","非盈利事业","公共事业","咨询","媒体","娱乐");
    private List<String> b= Arrays.asList("装修刚进", "暖通未定", "装修刚进场丶暖通已定", "装修未进场丶暖通已定", "装修未进场丶暖通未定");
    private List<String> d= Arrays.asList("潜在客户", "初步接触", "持续跟进", "成交客户", "忠诚客户");
    private List<String> c= Arrays.asList("网络推广", "电话销售", "渠道销售", "楼盘地推");
    private List<String> e= Arrays.asList("最终客户", "渠道客户", "竞争对手");
    private List<String> f= Arrays.asList("企业客户", "个人客户", "政府事业单位");
    private List<String> g= Arrays.asList("男", "女");

    private int xing;
    private Integer id;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BaseUtils.setStatusBar(this);
        inflater = LayoutInflater.from(this);
        binding = DataBindingUtil.inflate(inflater, R.layout.activity_member, null, false);
        setContentView(binding.getRoot());

        String data = getIntent().getStringExtra("data");
        if (StringUtils.isNotEmpty(data)) {
            BasicMember member = new Gson().fromJson(data, BasicMember.class);
            id=member.getId();
            binding.address.setText(member.getAddress());
            binding.project.setText(member.getProject());
            binding.huxing.setText(member.getHouseType());
            binding.mianji.setText(member.getMemo());
            binding.lianxiren.setText(member.getLianxiren());
            binding.lianxirenDianhua.setText(member.getLianxirenDianhua());
            binding.xingbie.setText(member.getJinzengGongsi());
            binding.kehuzhuangtai.setText(member.getZhuangxiuJindu());
            binding.kehujieduan.setText(member.getYezhuloucheng());
            binding.kehuleixing.setText(member.getYezhu());
            binding.kehuxingzhi.setText(member.getYezhuDianhua());
            binding.kehulaiyuan.setText(member.getJiechuRenqun());
            binding.kehuhangye.setText(member.getJiechuRenqunDianhua());
            binding.shangjikehu.setText(member.getYigouPinpai());
        }else {
            binding.address.setText(PreferenceUtil.getSharedPreference(Constant.CITY));
        }

        getHouse();
        getDemand();
        binding.huxing.setOnClickListener(v -> dialog());
        binding.kehuleixing.setOnClickListener(v -> kehuleixing());
        binding.kehuxingzhi.setOnClickListener(v -> kehuxingzhi());
        binding.kehujieduan.setOnClickListener(v -> demandDialog());
        binding.fileBtn.setOnClickListener(v -> startActivity(new Intent(MemberActivity.this, FileListActivity.class)));
        binding.dingwei.setOnClickListener(v -> startActivityForResult(new Intent(MemberActivity.this, MapSearchAddressActivity.class),1) );
        binding.submit.setOnClickListener(v -> submit());
        binding.kehulaiyuan.setOnClickListener(v -> kehulaiyuan());
        binding.kehuzhuangtai.setOnClickListener(v -> jindu());
        binding.xingbie.setOnClickListener(v -> xingbie());
        binding.kehuhangye.setOnClickListener(v -> kehuhangye());
        binding.back.setOnClickListener(v ->finish());

        binding.x1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                xing=1;
                binding.x1.setBackgroundResource(R.drawable.xing_red);
                binding.x2.setBackgroundResource(R.drawable.xing_gray);
                binding.x3.setBackgroundResource(R.drawable.xing_gray);
                binding.x4.setBackgroundResource(R.drawable.xing_gray);
                binding.x5.setBackgroundResource(R.drawable.xing_gray);
            }
        });
        binding.x2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                xing=2;
                binding.x1.setBackgroundResource(R.drawable.xing_red);
                binding.x2.setBackgroundResource(R.drawable.xing_red);
                binding.x3.setBackgroundResource(R.drawable.xing_gray);
                binding.x4.setBackgroundResource(R.drawable.xing_gray);
                binding.x5.setBackgroundResource(R.drawable.xing_gray);
            }
        });
        binding.x3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                xing=3;
                binding.x1.setBackgroundResource(R.drawable.xing_red);
                binding.x2.setBackgroundResource(R.drawable.xing_red);
                binding.x3.setBackgroundResource(R.drawable.xing_red);
                binding.x4.setBackgroundResource(R.drawable.xing_gray);
                binding.x5.setBackgroundResource(R.drawable.xing_gray);
            }
        });
        binding.x4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                xing=4;
                binding.x1.setBackgroundResource(R.drawable.xing_red);
                binding.x2.setBackgroundResource(R.drawable.xing_red);
                binding.x3.setBackgroundResource(R.drawable.xing_red);
                binding.x4.setBackgroundResource(R.drawable.xing_red);
                binding.x5.setBackgroundResource(R.drawable.xing_gray);
            }
        });
        binding.x5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                xing=5;
                binding.x1.setBackgroundResource(R.drawable.xing_red);
                binding.x2.setBackgroundResource(R.drawable.xing_red);
                binding.x3.setBackgroundResource(R.drawable.xing_red);
                binding.x4.setBackgroundResource(R.drawable.xing_red);
                binding.x5.setBackgroundResource(R.drawable.xing_red);
            }
        });
    }

    private void kehulaiyuan() {
        new SuperDialog.Builder(MemberActivity.this)
                .setGravity(Gravity.CENTER)
                .setTitle("客户来源", ColorRes.negativeButton)
                .setCanceledOnTouchOutside(false)
                .setItems(c, position -> {
                    binding.kehulaiyuan.setText(c.get(position));
                })
                .setNegativeButton("取消", null)
                .build();
    }
    private void kehuhangye() {
        new SuperDialog.Builder(MemberActivity.this)
                .setGravity(Gravity.CENTER)
                .setTitle("客户行业", ColorRes.negativeButton)
                .setCanceledOnTouchOutside(false)
                .setItems(a, position -> {
                    binding.kehuhangye.setText(a.get(position));
                })
                .setNegativeButton("取消", null)
                .build();
    }
    private void xingbie() {
        new SuperDialog.Builder(MemberActivity.this)
                .setGravity(Gravity.CENTER)
                .setTitle("性别", ColorRes.negativeButton)
                .setCanceledOnTouchOutside(false)
                .setItems(g, position -> {
                    binding.xingbie.setText(g.get(position));
                })
                .setNegativeButton("取消", null)
                .build();
    }
    private void kehuxingzhi() {
        new SuperDialog.Builder(MemberActivity.this)
                .setGravity(Gravity.CENTER)
                .setTitle("客户性质", ColorRes.negativeButton)
                .setCanceledOnTouchOutside(false)
                .setItems(f, position -> {
                    binding.kehuxingzhi.setText(f.get(position));
                })
                .setNegativeButton("取消", null)
                .build();
    }

    private void kehuleixing() {
        new SuperDialog.Builder(MemberActivity.this)
                .setGravity(Gravity.CENTER)
                .setTitle("客户类型", ColorRes.negativeButton)
                .setCanceledOnTouchOutside(false)
                .setItems(e, position -> {
                    binding.kehuleixing.setText(e.get(position));
                })
                .setNegativeButton("取消", null)
                .build();
    }

    private void jindu() {
        new SuperDialog.Builder(MemberActivity.this)
                .setGravity(Gravity.CENTER)
                .setTitle("客户状态", ColorRes.negativeButton)
                .setCanceledOnTouchOutside(false)
                .setItems(d, position -> {
                    binding.kehuzhuangtai.setText(d.get(position));
                })
                .setNegativeButton("取消", null)
                .build();
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String result = data.getExtras().getString("result");//得到新Activity 关闭后返回的数据
        if (StringUtils.isNotEmpty(result)){
            binding.address.setText(result);
        }
    }

    private void demandDialog() {
        new SuperDialog.Builder(MemberActivity.this)
                .setGravity(Gravity.CENTER)
                .setTitle("客户阶段", ColorRes.negativeButton)
                .setCanceledOnTouchOutside(false)
                .setItems(basicDemandList, position -> {
                    binding.kehujieduan.setText(basicDemandList.get(position));
                })
                .setNegativeButton("取消", null)
                .build();
    }

    private void dialog() {
        new SuperDialog.Builder(MemberActivity.this)
                .setGravity(Gravity.CENTER)
                .setTitle("选择户型", ColorRes.negativeButton)
                .setCanceledOnTouchOutside(false)
                .setItems(basicHouseList, position -> {
                    binding.huxing.setText(basicHouseList.get(position));
                })
                .setNegativeButton("取消", null)
                .build();
    }

    private void getHouse() {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().get().url(Urls.MEMBER_GETHOUSE).build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) { }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String result = response.body().string();
                    HouseModel vo = new Gson().fromJson(result, HouseModel.class);
                    if (vo.code != 200 || vo.data == null && vo.data.size() == 0) return;
                    basicHouseList.addAll(vo.data);
                }
            }
        });
    }

    private void getDemand() {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().get().url(Urls.MEMBER_GETDEMAND).build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String result = response.body().string();
                    HouseModel vo = new Gson().fromJson(result, HouseModel.class);
                    if (vo.code != 200 || vo.data == null && vo.data.size() == 0) return;
                    basicDemandList.addAll(vo.data);
                }
            }
        });
    }


    @SuppressLint("NewApi")
    private void submit() {
        if (Myappliction.fileEntityList.size() > 0) {
            for (FileEntity entity : Myappliction.fileEntityList) {
                if (StringUtils.isEmpty(entity.src)) {
                    Toast.makeText(MemberActivity.this, "当前还有文件正在上传，请稍后！", Toast.LENGTH_LONG).show();
                    return;
                }
            }
        }
        Map map = new HashMap();
        map.put("userId", PreferenceUtil.getSharedPreference(Constant.USERID));
        map.put("id", id);
        map.put("project", binding.project.getText().toString());
        map.put("address", binding.address.getText().toString());
        map.put("houseType", binding.huxing.getText().toString());
        map.put("memo", binding.mianji.getText().toString());
        map.put("yezhu", binding.kehuleixing.getText().toString());
        map.put("yezhuloucheng", binding.kehujieduan.getText().toString());
        map.put("yezhuDianhua", binding.kehuxingzhi.getText().toString());
        map.put("lianxiren", binding.lianxiren.getText().toString());
        map.put("lianxirenDianhua", binding.lianxirenDianhua.getText().toString());
        map.put("jiechuRenqun", binding.kehulaiyuan.getText().toString());
        map.put("jiechuRenqunDianhua", binding.kehuhangye.getText().toString());
        map.put("zhuangxiuJindu", binding.kehuzhuangtai.getText().toString());
        map.put("shangjikehu", binding.shangjikehu.getText().toString());
        map.put("jinzengGongsi", binding.xingbie.getText().toString());
        map.put("zhuangxiuGongsi", xing);
        map.put("yigouPinpai", binding.shangjikehu.getText().toString());
        map.put("files", Myappliction.fileEntityList.stream().map(FileEntity::getSrc).collect(Collectors.toList()));
        JSONObject jsonObject = new JSONObject(map);
        RequestBody requestBodyJson = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonObject.toString());
        okhttp3.Request requestPostJson = new okhttp3.Request.Builder().url(Urls.MEMBER_ADD).post(requestBodyJson).build();
        OkHttpClient okHttpClientPostJson = new OkHttpClient();
        okHttpClientPostJson.newCall(requestPostJson).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, okhttp3.Response response) throws IOException {
                String body = response.body().string();
                BaseEntity entity = new Gson().fromJson(body, BaseEntity.class);
                runOnUiThread(() -> Toast.makeText(MemberActivity.this, entity.msg, Toast.LENGTH_LONG).show());
                if (entity.code == 200) {
                    finish();
                }
            }
        });
    }

}
